package class04;

/**
 * @Auther: xw
 * @Create: 2022/3/16 9:16
 * @Description: 两个有序链表重排序  测试链接：https://leetcode.com/problems/merge-two-sorted-lists
 */
public class MergeTwoSortedLinkedList {
    // 不要提交这个类
    public static class ListNode {
        public int val;
        public ListNode next;
    }

    public static ListNode mergeTwoSortedLinkedList(ListNode head1,ListNode head2){
        if(null ==head1 || null == head2){
            return head1 == null ? head2 : head1;
        }
        //确定新链表的头结点
        ListNode head = head1.val <= head2.val ? head1 : head2;
        ListNode cur1 = head.next;
        ListNode cur2 = head == head1 ? head2 : head1;
        ListNode pre = head;

        while(cur1 != null && cur2 != null){
            if(cur1.val <= cur2.val){
                pre.next = cur1;
                cur1 = cur1.next;
            }else{
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }
        // TODO: 2022/3/16 某一个链表为空,只要将有另一个链表的下一个节点连接起来就ok
        pre.next = cur1 != null ? cur1 : cur2;
        return head;

    }
}
